package app.serialport;

import java.io.DataInputStream;
import java.io.IOException;

import org.apache.commons.lang3.ArrayUtils;

import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class SerialReader implements SerialPortEventListener {

	private SerialPort serialPort;
	private DataInputStream inStream;
	
	private byte[] buffer= new byte[40 * 1024];
	private int currentIndex = 0;
	private long start = System.currentTimeMillis();
	
	public SerialReader(DataInputStream inStream, SerialPort serialPort) {
		this.inStream = inStream;
		this.serialPort = serialPort;
	}
	
	@Override
	public void serialEvent(SerialPortEvent event) {
		// 定义用于缓存读入数据的数�?
		// 记录已经到达串口COM21且未被读取的数据的字节（Byte）数�?
		int availableBytes = 0;

		// 如果是数据可用的时间发�?，则进行数据的读�?
		try {
			availableBytes = inStream.available();
			while (availableBytes > 0) {
				int numBytes = inStream.read(buffer, currentIndex, availableBytes);

				currentIndex += numBytes;
				// for(int i = 0; i < cache.length && i < availableBytes;
				// i++){
				// //解码并输出数�?
				// System.out.print((char)cache[i]);
				// }
				// onDataRecived(data);

				availableBytes = inStream.available();
			}
//			System.out.println(currentIndex);
			byte[] data = ArrayUtils.subarray(buffer, 0, currentIndex);
			
			//String hexData = ByteUtil.bytes2HexString(data);
//			System.out.println(currentIndex + ": ");
//			System.out.println(hexData);
			
			byte[] message = serialPort.decoder.decode(data);
			if(message != null) {
				currentIndex = 0;
				serialPort.onDataRecived(message, System.currentTimeMillis() -start);
				
				start = System.currentTimeMillis();
			}
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
}